<template>
	<u-upload v-bind="$attrs" :fileList="fileList" @afterRead="afterRead" @beforeRead="beforeRead"
		@clickPreview="clickPreview" @delete="deleteFile" @oversize="oversize">
		<image v-if='styleImgUrl' :src="styleImgUrl" mode="widthFix" :style="styleString"></image>
		<slot v-else></slot>
	</u-upload>
</template>

<script>
	import Config from '@/config'
	export default {
		name: "uploadImage",
		props: {
			value: String,
			styleImgUrl: { //自定义图片路径，
				type: String,
				default: '',
			},
			styleString: { //自定义图片样式，不传则为默认
				type: String,
				default: '',
			}
		},

		computed: {

		},
		data() {
			return {
				fileList: []
			};
		},
		created() {
			this.fileList = this.$attrs.fileList || []
		},
		methods: {
			beforeRead(file, lists, name) {
				this.$emit('beforeRead', file, lists, name)
			},
			oversize(file, lists, name) {
				this.$emit('oversize', file, lists, name)
			},
			clickPreview(url, lists, name) {
				this.$emit('clickPreview', url, lists, name)
			},
			deleteFile(e) {
				this.fileList.splice(e.index, 1)
				this.$emit('delete', e)
			},
			afterRead(file, lists, name) {
				const that = this
				this.$emit('afterRead', file, lists, name)
				const attr = this.$attrs
				const params = attr.params || {
					params: {},
					custom: {},
					header: {},
					formData: {}
				}
				// 如果是单图
				let files = [].concat(file.file)
				if (!attr.multiple) {
					files = [file]
				}
				let uploadArr = [] // 上传成功数
				let fileListLen = this.fileList.length
				files.map(item => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let file of files) {
					uni.$u.http.upload(Config.baseUploadURL, {
						params: params.params,
						/* 会加在url上 */
						filePath: file.file ? file.file.url : file.url,
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: params.custom, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: attr.name || 'fileParam',
						// #ifdef H5 || APP-PLUS
						timeout: 60000,
						// #endif
						header: params.header,
						formData: params.formData,
					}).then(res => {
						let item = that.fileList[fileListLen]
						that.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: res
						}))
						uploadArr.push(res)
						that.$emit('success', res)
						if (uploadArr.length >= files.length) {
							// 全部上传完
							that.$emit('successAll', uploadArr)
						}
					})
				}
			}
		},
	};
</script>

<style lang="scss" scoped>
</style>